import websocket
import json
import time
import os
import subprocess

# OBS WebSocket 地址和端口
OBS_WEBSOCKET_URL = "ws://localhost:4455"
# 如果你在设置中定义了密码，请在此输入
OBS_WEBSOCKET_PASSWORD = "R9IK6k16wY30rp87"

def connect_to_obs():
    """建立 WebSocket 连接"""
    try:
        ws = websocket.create_connection(OBS_WEBSOCKET_URL)
        print("连接成功")
        auth_message = json.dumps({
            "op": 1,
            "d": {
                "rpcVersion": 1,
                "authentication": OBS_WEBSOCKET_PASSWORD
            }
        })
        ws.send(auth_message)
        return ws
    except Exception as e:
        print(f"连接失败: {e}")
        return None

def start_recording(ws):
    """发送开始录制命令"""
    start_record_message = json.dumps({
        "op": 6,
        "d": {
            "requestType": "StartRecord",
            "requestId": "start_record"
        }
    })
    ws.send(start_record_message)
    print("开始录制命令发送成功")
    # 接收响应
    response = ws.recv()
    print("接收到的响应:", response)

def stop_recording(ws):
    """发送停止录制命令"""
    stop_record_message = json.dumps({
        "op": 6,
        "d": {
            "requestType": "StopRecord",
            "requestId": "stop_record"
        }
    })
    ws.send(stop_record_message)
    print("停止录制命令发送成功")
    # 接收响应
    response = ws.recv()
    print("接收到的响应:", response)

def sleep(s):
    time.sleep(s)
def launch_obs():
    sleep(2)
    file_path = "D:\Software\obs-studio\bin\64bit\obs64.exe"
    #C:\Program Files\Star Rail\Game\StarRail.exe
    game_name = os.path.basename(file_path)
    call = 'TASKLIST','/FI',f'imagename eq {game_name}'
    output = subprocess.check_output(call).decode('cp1252')
    if game_name in output:
        isLaunchGame = True
        print(111111)
    else:
        isLaunchGame = False
        print(2222222)
    
    #isLaunchGame = True
    '''
    if not isLaunchGame:
        print("not running")
        try:
            # 调用subprocess模块来启动.exe文件
            # subprocess.Popen(file_path,creationflags=subprocess.CREATE_NEW_CONSOLE)
            game_process = subprocess.Popen(['start', '', file_path], shell=True)
            result = 1
        except FileNotFoundError as e:
            print("未能找到指定的.exe文件")
            result = 0
        except Exception as e:
            print("发生错误：", str(e))
            result = 0
            
        if(result == 0):
            print("脚本结束...")
            exit()
        else:
            print("等待游戏启动...")
            bar=getBar(60)

            #启动程序到加载窗口出来
            for i in range(60):
                #print(str(i)+"-",end="")
                sleep(1) #等待游戏启动
                bar.update(i)
                if any(game_title in win.title for win in pygetwindow.getWindowsWithTitle(game_title)):
                    break
            bar.finish()

            #初始化位置，将程序放到左上角
            getXY()

            print("窗口加载开机动画，等待 点击进入游戏 按钮")
            bar.start()
            flag_again = 0
            for i in range(30):
                sleep(1) #等待游戏启动
                bar.update(i)
                loc = getpngfromShot2("点击进入游戏",_show_print=False)
                if loc!=0:
                    flag_again+=1
                if flag_again>4:
                    break
                # click(500,500)
            # sleep(20)
            bar.finish()
            click(500,500) # 点击进入游戏


            #点击进入游戏 到 游戏画面
            print("点击进入游戏 到 游戏画面")
            bar.start()
            for i in range(30):
                sleep(1) #等待游戏启动
                bar.update(i)
                # press("tab")
                loc = getpngfromShot2("队员界面",_show_print=False)
                if loc!=0:
                    break
                # click(500,500)
            # sleep(20)
            bar.finish()

            print("游戏加载完毕。。。")        
    else:
        print("running")
        getXY()
        '''
def connect_obs():
    # 连接到 OBS
    ws = connect_to_obs()

    if ws is not None:
        # 开始录制
        start_recording(ws)

        # 停止录制（可根据实际需求设置等待时间或条件）
        # input("按回车键停止录制...")
        time.sleep(5)
        stop_recording(ws)

        # 关闭连接
        ws.close()

if __name__ == "__main__":
    launch_obs()
